package com.app.controller;

import com.app.model.*;
import com.app.service.*;
import com.app.util.CommonHelp;
import com.app.util.DateUtil;
import com.app.util.Result;
import com.app.util.TokenUtils;
import com.app.vo.TrainVo;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;


@Controller
@ResponseBody
public class TainEnrollController {


    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    private TrainEnrollService trainEnrollService;

    @Autowired
    AdminUserService adminUserService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private UserService userService;

    @GetMapping("/findTrainEnroll")
    public Result<Object> findTrainEnroll(HttpServletRequest request
    ) throws ParseException {
        TrainEnrollModel model = new TrainEnrollModel();
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");

        }
        String mobile = TokenUtils.verify(token);
        UserModel user = userService.getUserByMobile(mobile);
        if (user == null) {
            return Result.error(405, "用户不存在");
        }
        CustomerModel cus = customerService.getCustomerById(user.getCId());
        model.setCid(cus.getId());
        trainEnrollService.selectByCid(model);
        if (trainEnrollService.selectByCid(model) == null) {
            int sentry = 1;
            return Result.success(sentry);
        } else {
            int sentry = 2;
            return Result.success(sentry);
        }
    }

    //增
    @PostMapping("/groupTrainEnroll")
    public Result<Object> groupTrainEnroll(@RequestParam("realName") String realName,
                                           @RequestParam("sid") int sid,
                                           @RequestParam("mobile") String mobile,
                                           @RequestParam("isRid") Integer isRid,
                                           HttpServletRequest request
    ) throws ParseException {
        TrainEnrollModel model = new TrainEnrollModel();
        model.setRealName(realName);
        model.setSid(sid);
        model.setMobile(mobile);
        model.setIsRid(isRid);
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");

        }
        String phone = TokenUtils.verify(token);
        UserModel user = userService.getUserByMobile(phone);
        if (user == null) {
            return Result.error(405, "用户不存在");
        }
        CustomerModel cus = customerService.getCustomerById(user.getCId());
        model.setCid(cus.getId());
        model.setCrtTime(CommonHelp.getNowTimestamp().toString());

        int count = trainEnrollService.selectByPhone(model);
        if (count > 0) {
            return Result.success("已报名,请勿重复报名");
        } else {
            trainEnrollService.insert(model);
            return Result.success("报名成功");
        }
    }

    //删除
    @PostMapping("/delTrainEnroll")
    public Result<Object> delTrainEnroll(@RequestParam("id") int id) {
        JSONObject json = new JSONObject();
        try {
            if (id > 0) {
                trainEnrollService.delete(id);
            } else {
                Result.error(500, "请输入id");
            }

        } catch (Exception e) {
            System.out.println(e);
        }
        return Result.success(null);
    }

    //查询培训列表
    @GetMapping("/getTrainEnrollList")
    public Result<Object> getTrainingList(HttpServletRequest request) throws ParseException {
        String sid = request.getParameter("sid");
        String id = request.getParameter("id");
        String token = request.getHeader("access-token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        JSONObject json = new JSONObject();
        TrainEnrollModel model = new TrainEnrollModel();
        String mobile = TokenUtils.verify(token);
        UserModel user = userService.getUserByMobile(mobile);
        if (user == null) {
            return Result.error(405, "用户不存在");

        }
        CustomerModel cus = customerService.getCustomerById(user.getCId());
        model.setCid(cus.getId());
        if (sid != null && sid != "") {
            model.setSid(Integer.valueOf(sid));
        }

        if (id != null && id != "") {
            model.setId(Integer.valueOf(id));
        }
        List<TrainEnrollModel> modelList = trainEnrollService.getSkillTrainingList(model);
        if (modelList != null && modelList.size() > 0) {
            json.put("data", modelList);
            return Result.success(modelList);
        }
        return null;
    }

    @Autowired
    private TrainTypeConfigSonService trainTypeConfigSonService;
    @Autowired
    private ConfigService configService;

    @GetMapping("/getRegistrationInformation")
    public Result<Object> getSpecialityById(
            @RequestParam(value = "id") Integer id,
            HttpServletRequest request) {
//        String token = request.getHeader("access-token");
//        if (token == null) {
//            return Result.error(405, "token不存在");
//        }
//        String mobile = TokenUtils.verify(token);
//        UserModel user = userService.getUserByMobile(mobile);
//        if (user == null) {
//            return Result.error(405, "用户不存在");
//
//        }
        TrainEnrollModel train = this.trainEnrollService.selectById(id);
        TrainTypeConfigSonModel model = trainTypeConfigSonService.getModelById(train.sid);
        ConfigModel config = configService.getModelById(model.getConfigId());
        model.setConfigIdText(config.getName());
        model.setDayText(DateUtil.dayCompare(model.getStartTime(), model.getEndTime()).getDay());

        model.setEnrollModelInfo(train);

        return Result.success(model);
    }


    //我的报名
    @GetMapping("/myApplication")
    public Result<Object> myApplication(Integer page, Integer limit, Integer status, HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String phone = TokenUtils.verify(token);
        UserModel user = userService.getUserByMobile(phone);
        if (user == null) {
            return Result.error(405, "用户不存在");
        }
        CustomerModel customerByCid = customerService.getCustomerByCid(user.getCId());
        if (customerByCid == null) {
            return Result.error(405, "请完善个人信息");
        }
        Page<TrainEnrollModel> modelPage = trainEnrollService.myApplication(page, limit, status, customerByCid);
        TrainVo vo = new TrainVo();
        vo.setCount((int) modelPage.getTotal());
        vo.setList(modelPage.getRecords());
        for (int i = 0; i < vo.getList().size(); i++) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            Timestamp data = Timestamp.valueOf(vo.getList().get(i).getCrtTime());
            String currentSimpleDateFormat = simpleDateFormat.format(data);
            vo.getList().get(i).setCrtTime(currentSimpleDateFormat);
        }
        return Result.success(vo);
    }

    //审核
    @GetMapping("/applicationExamine")
    public Result<Object> applicationExamine(Integer id, Integer status, String remark, HttpServletRequest request) {
        String token = request.getHeader("token");
        String userId = TokenUtils.nothingness(token);
        if (userId == null) {
            return Result.error(405, "token不存在");
        }
        AdminUserModel user = adminUserService.getUserById(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(405, "用户不存在");
        }
        String s = trainEnrollService.applicationExamine(id, status, remark);
        return Result.success(s);
    }
}
